<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box{width: 100px;height: 100px;background: blue;position: absolute;left: 0;top: 0;}
    </style>
</head>
<body>
    <div id="box"></div>
    <script>
        var obox = document.getElementById("box");

        

        obox.addEventListener('mousedown',function(eve){
            var downE = eve || window.event;
            function fn1(eve){
                var moveE = eve || window.event;

                var l = moveE.pageX - downE.offsetX;
                var t = moveE.pageY - downE.offsetY;
                
                if(l<0) l=0;
                if(t<0) t=0;
                if(l > document.documentElement.clientWidth-obox.offsetWidth){
                    l = document.documentElement.clientWidth-obox.offsetWidth
                }
                if(t > document.documentElement.clientHeight-obox.offsetHeight){
                    t = document.documentElement.clientHeight-obox.offsetHeight
                }

                obox.style.left = l + "px";
                obox.style.top = t + "px";

            }
            document.addEventListener('mousemove',fn1)
            document.addEventListener('mouseup', function fn2(){
                document.removeEventListener('mousemove',fn1);
                document.removeEventListener('mouseup',fn2);
            })
        })



        // function addEvent(ele, type, cb){
        //     if(ele.attachEvent){
        //         ele.attachEvent("on"+type, cb);
        //     }else{
        //         ele.addEventListener(type, cb);
        //     }
        // }
    </script>
</body>
</html>